package com.user.dao;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.user.vo.User;
import com.user.service.UserQryHelper;

public class UserDaoHibernateImpl extends HibernateDaoSupport implements UserDao {

	public void addUser(User user) {
		this.getHibernateTemplate().save(user);

	}

	public void deleteUser(User user) {
		User userTemp = (User)this.getHibernateTemplate().load(User.class, user.getUserId());
		this.getHibernateTemplate().delete(userTemp);

	}

	public Integer getCountUsers(UserQryHelper helper) {
		DetachedCriteria criteria=this.buildCriteria(helper);
		criteria.setProjection(Projections.rowCount());
		return (Integer)this.getHibernateTemplate().findByCriteria(criteria).get(0);
	}

	public User getUserById(Integer uId) {
		return (User)this.getHibernateTemplate().get(User.class, uId);
	}

	public List<User> loadAll(int startIndex, int fetchSize,
			UserQryHelper helper) {
		DetachedCriteria criteria=this.buildCriteria(helper);
		List<User> users = this.getHibernateTemplate().findByCriteria(criteria, startIndex - 1, fetchSize);
		return users;
	}

	public void updateUser(User user) {
		this.getHibernateTemplate().update(user);

	}
	
	private DetachedCriteria buildCriteria(UserQryHelper helper)
	{
		
		DetachedCriteria criteria=DetachedCriteria.forClass(User.class);
		
		if (StringUtils.isNotEmpty(helper.getUserNo()))
			criteria.add(Restrictions.like("userNo", helper.getUserNo().trim(), MatchMode.ANYWHERE));

		if (StringUtils.isNotEmpty(helper.getUserName()))
			criteria.add(Restrictions.like("userName", helper.getUserName().trim(), MatchMode.ANYWHERE));
		
		if (StringUtils.isNotEmpty(helper.getUserStatus()))
			criteria.add(Restrictions.like("userStatus", helper.getUserStatus().trim()));
		
		if (helper.getSortHelper() != null){
			if(helper.getSortHelper().getSortedType().equals("desc"))
			   criteria.addOrder(Property.forName(helper.getSortHelper().getColName()).desc());
			else
			   criteria.addOrder(Property.forName(helper.getSortHelper().getColName()).asc());	
		}
		
		return criteria;
	}

}
